const { app, globalShortcut, BrowserWindow } = require('electron');
const CoreWindow = require('ee-core/electron/window');
const Log = require('ee-core/log');
const EE = require('ee-core/ee');


const SHORTCUT_QUIT = 'Esc';

/**
 * 快捷键插件
 * @class
 */
class ShortCutAddon {

  constructor() {
    this.tray = null;
  }

  /**
   * 创建快捷键
   */
  create () {
    Log.info('[addon:shortcut] load');
    if (globalShortcut.isRegistered(SHORTCUT_QUIT)) {
        globalShortcut.unregister(SHORTCUT_QUIT)
    }
    const { CoreApp } = EE;
    // electron 多个页面注册快捷键 实现Esc关闭最前面的窗口
    app.whenReady().then(() => {
        app.on('browser-window-focus',()=>{
            globalShortcut.register(SHORTCUT_QUIT, function() {
              let focusWin = BrowserWindow.getFocusedWindow();
              if (CoreWindow.getMainWindow() === focusWin) {
                Log.info("[addon:shortcut] Esc Quit:" + focusWin.getTitle())
                CoreApp.appQuit();
                return;
              }
              if (focusWin){
                Log.info("[addon:shortcut] close focusWin:" + focusWin.getTitle())
                focusWin.close();
              }
            })
        })
    })

    app.on('will-quit', () => {
        // 当应用程序退出时，解除所有已注册的快捷键
        globalShortcut.unregisterAll()
        Log.info("[addon:shortcut] will-quit：unregisterAll")
    })

  }
}

ShortCutAddon.toString = () => '[class ShortCutAddon]';
module.exports = ShortCutAddon;